package de.velvettear.squirrel.util;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

public class GPSHelper {
	
	private static Handler handler;
	private static LocationManager locManager;
	
	public static void getLastKnowLocation(Handler handler, Context context) {
		Log.i("getLastKnowLocation()", "BEGIN");
		
		GPSHelper.handler = handler;
		if (locManager == null) {
			locManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);			
		}
		Location loc = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		Log.i("getLastKnowLocation()", "LAST KNOWN LOCATION " + String.valueOf(loc.getLatitude()) + ", " + String.valueOf(loc.getLongitude()));
		
		Log.i("getLastKnowLocation()", "END");
	}
	
	public static void startTracking(Handler handler, Context context) {
		Log.i("startTracking()", "BEGIN");
		GPSHelper.handler = handler;
		
		if (locManager == null) {
			locManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);			
		}
		locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 0, locListener); 
		
		Log.i("startTracking()", "END");
	}
	
	public static void stopTracking(Context context) {
		Log.i("stopTracking()", "BEGIN");
		if (locManager != null) {
			locManager.removeUpdates(locListener);
			locManager = null;			
		}
		Log.i("stopTracking()", "END");
	}
	
	public static String getGoogleMapsLink(Location loc) {
		Log.i("getGoogleMapsLink()", "BEGIN");
		String link = "http://maps.google.com/maps?q=" + String.valueOf(loc.getLatitude()) + "," + String.valueOf(loc.getLongitude()) + "&ll=" + String.valueOf(loc.getLatitude()) +"," + String.valueOf(loc.getLongitude()) + "&z=17";
		Log.i("getGoogleMapsLink()", "END");
		return link;
	}
	
	public static LocationListener locListener = new LocationListener() {

		@Override
		public void onLocationChanged(Location location) {
			Log.i("startTracking()", "LOCATION CHANGED " + String.valueOf(location.getLatitude()) + ", " + String.valueOf(location.getLongitude()));		
		}

		@Override
		public void onProviderDisabled(String provider) {
			
		}

		@Override
		public void onProviderEnabled(String provider) {
			
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			
		}
		
	};
	
}
